# !/usr/bin/env python

import sys
import time
import hashlib
import os
import oss2
from itertools import islice
import datetime


today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
backuptime = yesterday.strftime('%Y-%m-%d')


# 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
auth = oss2.Auth('LTAI4FteGCWYNVPas61vx5sJ', 'bUqjfENA2R****')
# Endpoint以杭州为例，其它Region请按实际情况填写。
bucket = oss2.Bucket(
    auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'backup')


def print_run_time(func):
    def wrapper(*args, **kw):
        local_time = time.time()
        func(*args, **kw)
        print('[+] [%s] Run time is %.2f' %
              (func.__name__, time.time() - local_time))
    return wrapper


@print_run_time
def CheckMD5(filename, md5file):
    if os.path.isfile(filename) and os.path.isfile(md5file):
        res = hashlib.md5(open(filename, 'rb').read()).hexdigest()
        with open(md5file) as f:
            if f.read() == res:
                print('ok')
            else:
                print('对比失败')
                sys.exit(1)
    else:
        print("""[-] 文件不存在! 请检查下列文件:\n%s、%s""" % (filename, md5file))
        sys.exit(1)


# 下载文件
@print_run_time
def download(filename):
    s = bucket.get_object_to_file(filename, filename)
    if s.status == 200:
        print("""[+] "%s" 下载成功 """ % filename)
    else:
        print("""[-] "%s" 下载失败! %d""" % (filename, s.status))


@print_run_time
def delete(filename):
    prefix = filename  # 定义要删除的前缀文件
    for obj in oss2.ObjectIterator(bucket, prefix=prefix):
        # print(obj.key)
        if obj.key:
            bucket.delete_object(obj.key)
            print("[+] 删除文件: %s" % obj.key)

# 执行命令
@print_run_time
def cmdrun(command):
    res = os.system(command)
    return res


def display():
    # oss2.ObjectIteratorr用于遍历文件。
    print("目录列表:\n")
    for b in islice(oss2.ObjectIterator(bucket), 10):
        print(b.key)


if __name__ == '__main__':
    backupfile = "recognize_log.%s.sql" % backuptime
    backupfile_md5 = '%s.md5' % backupfile
    download(backupfile_md5)  # 下载md5
    download(backupfile)  # 下载文件
    CheckMD5(backupfile, backupfile_md5)

    print("[+] 下载成功 继续")
    delete(backupfile)
    print("[+] OSS文件已经删除")
    display()
    cmdrun("mysql  recognize < %s" % backupfile)
    print("[+] 数据恢复到本地数据库")
    table_time = backuptime.replace('-', '_')
    cmdrun("mysql -e 'rename table    recognize.recognize_log_all to  recognize.recognize_log_%s'" % table_time)
    print("[+] 数据恢复到本地数据库")
